const {
    callContainerApi,
    updateCartBadge
} = require('../../utils/util.js')

Page({
    data: {
        cartList: [],
        totalPrice: 1,
        totalCount: 0,
        allChecked: false,
        checkedList: []
    },

    onLoad() {},
    onShow() {
        wx.showLoading({
            title: '加载中...'
        });

        // 模拟异步加载
        setTimeout(() => {
            const cartList = wx.getStorageSync('cartList') || [];
            const updates = {};

            cartList.forEach((item, index) => {
                item.checked = false;
                item.image = item.image || '/images/default-product.png';
                // 只更新变化的字段
                updates[`cartList[${index}].checked`] = false;
                updates[`cartList[${index}].image`] = item.image;
            });

            this.calculateTotal(cartList);
            this.setData({
                cartList,
                ...updates
            }, () => {
                wx.hideLoading();
            });
        }, 300);
    },

    onImageError(e) {
        const index = e.currentTarget.dataset.index;
        let cartList = this.data.cartList;
        cartList[index].image = '/images/default-product.png';
        this.setData({
            cartList
        });
    },
    decreaseCount(e) {
        const index = e.currentTarget.dataset.index;
        let cartList = this.data.cartList;
        if (cartList[index].num > 1) {
            cartList[index].num--;
            this.updateCartList(cartList);
        } else {
            cartList.splice(index, 1);
            this.updateCartList(cartList);
            // 强制更新视图并重新计算总价
            this.setData({
                cartList: [...cartList]
            }, () => {
                this.calculateTotal(cartList);
            });
        }
    },
    increaseCount(e) {
        const index = e.currentTarget.dataset.index;
        let cartList = this.data.cartList;
        cartList[index].num++;
        this.updateCartList(cartList);
    },
    removeFromCart(e) {
        const index = e.currentTarget.dataset.index;
        let cartList = this.data.cartList;
        cartList.splice(index, 1);
        this.updateCartList(cartList);
    },
    updateCartList(cartList) {
        // 数据清理和格式化
        const cleanedCartList = cartList.map(item => {
            // 确保使用num字段，移除count字段
            const cleanedItem = {
                ...item,
                num: Number(item.num || item.count || 1), // 兼容旧数据
                price: Number(item.price || 0)
            };
            if ('count' in cleanedItem) {
                delete cleanedItem.count;
            }
            return cleanedItem;
        });

        wx.setStorageSync('cartList', cleanedCartList);
        this.calculateTotal(cleanedCartList);
        this.setData({
            cartList: cleanedCartList
        });
        updateCartBadge();
    },
    calculateTotal(cartList) {
        let totalPrice = 0;
        let totalCount = 0;
        let checkedList = [];
        cartList.forEach(item => {
            // 确保价格和数量是数字类型
            item.price = Number(item.price) || 0;
            item.num = Number(item.num) || 1;

            // 计算总数量（不管是否选中）
            totalCount += item.num;

            if (item.checked) {
                totalPrice += item.price * item.num;
                checkedList.push(item);
            }
            // 添加格式化后的价格字段
            item.formattedPrice = (item.price * item.num).toFixed(2);
            item.formattedUnitPrice = item.price.toFixed(2);
        });
        const allChecked = cartList.length > 0 && cartList.every(item => item.checked);
        this.setData({
            totalPrice: totalPrice.toFixed(2),
            totalCount,
            allChecked,
            checkedList,
            cartList
        });

        // 更新tabBar购物车数量
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                cartCount: totalCount
            });
        }
    },
    checkout() {
        const {
            checkedList,
            totalPrice
        } = this.data;
        if (checkedList.length === 0) {
            wx.showToast({
                title: '请选择商品',
                icon: 'none'
            });
            return;
        }

        let postMessage = []
        for (const item of checkedList) {
            const temp = {
                "merchandiseId": item.id,
                "merchandiseName": item.name,
                "specId": item.specId,
                "specDesc": item.spec,
                "singlePrice": item.price,
                "num": item.num
            }
            postMessage.push(temp)
        }
        const merchantId = wx.getStorageSync('merchantId')

        callContainerApi(`/order/generate?totalPrice=${totalPrice}&merchantId=${merchantId}`, "POST", postMessage)
            .then(res => {
                if (res.data.code === 501) {
                    wx.showModal({
                        title: '没有收货地址，请添加',
                        complete: (res) => {
                            if (res.cancel) {
                                return
                            }
                            if (res.confirm) {
                                wx.navigateTo({
                                    url: '/pages/addAddress/addAddress',
                                })
                            }
                        }
                    })
                } else {
                    let cartList = this.data.cartList.filter(item => !item.checked)
                    // 删除添加到订单中的购物车商品
                    this.updateCartList(cartList)
                    updateCartBadge()
                    const orderId = res.data.data.id
                    wx.showModal({
                        title: '是否跳转到订单页面',
                        complete: (res) => {
                            if (res.cancel) {
                                return
                            }
                            if (res.confirm) {
                                wx.navigateTo({
                                    url: `/pages/orderDetail/orderDetail?id=${orderId}`,
                                })
                            }
                        }
                    })
                }
            })
    },

    pay() {

      setTimeout(() => {
      }, 1500000);
        wx.cloud.callFunction({
            name: 'cloudbase_module',
            data: {
                // 工作流ID, 需从工作流属性中获取
                name: 'sywxzfapifqzf_6bd7f03',
                data: {
                    description: "商品支付",
                    out_trade_no: Math.round(Math.random() * 10 ** 13) + Date.now(),
                    amount: {
                        total: 10,
                        currency: "CNY"
                    }
                }
            },
            success: res => {
                console.log('下单结果: ', res);
                // 获取到预付单信息
                const paymentData = res.result?.data;
                // 唤起微信支付组件，完成支付
                wx.requestPayment({
                    timeStamp: paymentData?.timeStamp,
                    nonceStr: paymentData?.nonceStr,
                    package: paymentData?.packageVal,
                    paySign: paymentData?.paySign,
                    signType: "RSA", // 该参数为固定值
                    success(res) {
                        // 支付成功回调，实现自定义的业务逻辑
                        console.log('唤起支付组件成功：', res);
                    },
                    fail(err) {
                        // 支付失败回调
                        console.error('唤起支付组件失败：', err);
                    }
                });
            },
        });
    },
    checkAll(e) {
        const allChecked = !this.data.allChecked;
        let cartList = this.data.cartList;
        cartList.forEach(item => {
            item.checked = allChecked;
        });
        this.setData({
            allChecked
        });
        this.updateCartList(cartList);
    },
    checkItem(e) {
        const index = e.currentTarget.dataset.index;
        let cartList = wx.getStorageSync('cartList')
        cartList[index].checked = !cartList[index].checked;
        this.updateCartList(cartList);
    },
    deleteChecked() {
        let cartList = this.data.cartList.filter(item => !item.checked);
        this.updateCartList(cartList);
    },

    // 跳转到首页
    goToIndex() {
        wx.switchTab({
            url: '/pages/index/index'
        });
    },

    // 微信订阅消息测试 ========================================》
    registermessage(){
        console.log("test")
        wx.requestSubscribeMessage({
            tmplIds: ['OO3j2utKf6Poaq3Hw7cf_lDqM7io-sbukgrfhvMbnm8', 'r8xfUwRwYtKDoJ8YWRP1ProZqNgabG_LmnVfUuvCtDs'],
            success(res) {
              console.log('订阅消息授权结果：', res)
            },
            fail(res){
                console.log("订阅消息出错",res)
            }
          });
    },
    sendmessage(){
        callContainerApi(`/order/finish?orderId=100022`, "POST", null)
        .then(res => {
          console.log('success',res)
        }).catch(err => {
         console.log('error',res)
        })
    }
    // 《========================================微信订阅消息测试
});